import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

import { routes } from "@/router/routes";

import NProgress from "nprogress";
import "nprogress/nprogress.css";

import {validPermission} from '@/utils'

// 用户信息store
import { UserState } from "@store/types";
import useUserStore from "@store/modules/user";
// 用pina代替vuex进行状态管理，取代了vuex中的mutation，只有state，getter， action
import pinia from "@store/pinia";
// 传入pinia，是为了激活pinia，以实现全局调用，防止pinia实例在全局调用时未挂载
const userStore = useUserStore(pinia);
import { getTokenUser } from "@/request/apis/login";

// 定义路由接口，根据实际接口返回值进行修改
//#region
export interface OriginRoute {
  icon: string;
  url: string;
  mname: string;
  permission: string;
  pid: string;
  id: number; //string;
  type: number;
  children?: Array<OriginRoute>;
  outLink?: string;
  sort: number;
  component: string;
  componentName: string;
  status: number;
  visible: boolean;
  keepAlive: boolean;
  alwaysShow: boolean;
  createTime: string;
  [propName: string]: any;
}
//#endregion


// 创建路由实例并传递“routes”配置
const router = createRouter({
  history: createWebHashHistory(),
  routes: routes, 
});

// 进度条动画
NProgress.configure({
  showSpinner: false,
});

// 路由白名单，无需鉴权的路由
const whiteRoutes: string[] = ["/login"];

//路由过滤
router.beforeEach((to, from, next) => {
  NProgress.start();
  userStore.clearAllRequest(); // 跳转的时候清空上个页面的所有请求

  const { token, isHasGetInfo , userInfo:{permissions}} = userStore;
  // token 存在
  if (token) {
    if(!isHasGetInfo){//如果本地信息不存在了
      getTokenUser().then((data) => {
        const userInfo = {
          id: data.id,
          avatar: data.avatar,
          name: data.uname, //用户名
          loginName: data.loginName, //用户登录账号
          orgId: data.deptid,
          permissions: data.permissions, //权限
        };
        userStore.saveUser(userInfo as UserState);          
        userStore.saveMenus(data.menuList, "pid", "id");
      }).catch((err) => {
        userStore.removeUserInfo();
        next({ name: "login", replace: true });
      });
    }
    NProgress.done();
    if (to.name === "login") {
      next({ name: "home" });   //token存在跳转的还是登陆页，则跳转到首页
    } else {
      // token存在且跳转的不是登陆页，则需要判断权限
      let hasPermisson = true;
      if(to.meta.permisson){
          hasPermisson = validPermission(permissions,to.meta.permisson as string)
      }
      if (hasPermisson) { // 有权限
        next();
      } else {//无权限
        ElMessage.error("无访问权限！");
        return false;
      }
    }
  } else {
    // token不存在
    NProgress.done();
    if (whiteRoutes.includes(to.path)) {
      NProgress.done();
      next();
    }else{
      next({ name: "login", replace: true });
    }
  }
  
});

router.afterEach(() => {
  NProgress.done();
});

export default router;
